package com.woniuxy.flter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.config.JwtUtil;
import com.woniuxy.config.UnLoginProperties;
import com.woniuxy.config.UserConst;
import com.woniuxy.exception.WoniuxyException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Component
@Order(1)
public class MyGlobaleFilter implements GlobalFilter {

    private ObjectMapper om = new ObjectMapper();
    @Resource
    private UnLoginProperties unLoginProperties;

    private AntPathMatcher apm = new AntPathMatcher();

    @Resource
    private JwtUtil jt;

    public boolean isUnlogin(String uri){
        for (String s : unLoginProperties.getUri()) {
            if( apm.match(s,uri)){
                return true;
            }
        }
        return false;
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("========全局拦截器===========");
        if(isUnlogin(exchange.getRequest().getPath().toString())){
            return chain.filter(exchange);
        }else{
            List<String> tokens = exchange.getRequest().getHeaders().get(UserConst.USER_TOKEN);
            if(tokens==null||tokens.size()<=0){
                throw new WoniuxyException(401,"未登录");
            }
            String s = tokens.get(0);
            try {
                jt.parse(s);
            } catch (Exception e) {
                throw new WoniuxyException(401,"未登录");
            }
            return chain.filter(exchange);
        }
    }


}